package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.service.TimeLineService;
import com.tanhua.dubbo.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import model.mongo.Movement;
import model.mongo.MovementTimeLine;
import model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
@Slf4j
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;


    @Override
    public void publish(Movement movement) {
        try {
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);

            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Movement.class);

        query.skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page, pagesize, count, movements);
    }

    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long friendId) {

        /*//1、根据friendId查询时间线表
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .skip((page -1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lineList = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id列表
        List<ObjectId> list = CollUtil.getFieldValues(lineList, "movementId", ObjectId.class);
        //3、根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(list));
        return mongoTemplate.find(movementQuery,Movement.class);*/
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(
                Query.query(
                        Criteria.where("friendId").is(friendId))
                        .skip((page - 1) * pagesize)
                        .limit(pagesize)
                        .with(Sort.by(Sort.Order.desc("created"))),
                MovementTimeLine.class);
        List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        log.info(movementIds.toString());
        return mongoTemplate.find(Query.query(Criteria.where("id").in(movementIds)), Movement.class);
    }

    @Override
    public List<Movement> randomMovements(Integer pagesize) {
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(pagesize));
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(aggregation, Movement.class);
        return aggregate.getMappedResults();
    }

    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        return mongoTemplate.find(Query.query(Criteria.where("pid").in(pids)), Movement.class);
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }

    @Override
    public PageResult findByUserId(Long uid, Integer state, Integer page, Integer pagesize) {
        Query query = new Query();
        if(uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }

        long count = mongoTemplate.count(query, Movement.class);
        //设置分页参数
        query.with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize).skip((page -1) * pagesize);

        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }


}